﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Specialized;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using log4net;
using SubSonic;

namespace AppBox
{
    public class PageBase : System.Web.UI.Page
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region OnInit

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            UpdateOnlineUser(User.Identity.Name);

            // 设置页面标题
            Page.Title = String.Format("{0} - {1}", Page.Title, XConfigHelper.Title);
        }

        #endregion

        #region GetQueryValue/GetQueryIntValue

        /// <summary>
        /// 获取查询字符串中的参数值
        /// </summary>
        protected string GetQueryValue(string queryKey)
        {
            return Request.QueryString[queryKey];
        }


        /// <summary>
        /// 获取查询字符串中的参数值
        /// </summary>
        protected int GetQueryIntValue(string queryKey)
        {
            int queryIntValue = -1;
            try
            {
                queryIntValue = Convert.ToInt32(Request.QueryString[queryKey]);
            }
            catch (Exception)
            {
                // TODO
            }

            return queryIntValue;
        }

        #endregion

        #region PageIndex/TotalCount/PageSize

        /// <summary>
        /// 当前显示第几页（从1开始）
        /// </summary>
        protected int PageIndex
        {
            get
            {
                if (ViewState["PageIndex"] == null)
                {
                    ViewState["PageIndex"] = 1;
                }
                return Convert.ToInt32(ViewState["PageIndex"]);
            }
            set
            {
                ViewState["PageIndex"] = value;
            }
        }
        /// <summary>
        /// 总共多少条记录
        /// </summary>
        protected int TotalCount
        {
            get
            {
                if (ViewState["TotalCount"] == null)
                {
                    ViewState["TotalCount"] = 0;
                }
                return Convert.ToInt32(ViewState["TotalCount"]);
            }
            set
            {
                ViewState["TotalCount"] = value;
            }
        }

        /// <summary>
        /// 每页显示多少条记录
        /// </summary>
        protected int PageSize
        {
            get
            {
                if (ViewState["PageSize"] == null)
                {
                    ViewState["PageSize"] = XConfigHelper.PageSize;
                }
                return Convert.ToInt32(ViewState["PageSize"]);
            }
            set
            {
                ViewState["PageSize"] = value;
            }
        }

        /// <summary>
        /// 总共有多少页
        /// </summary>
        protected int PageCount
        {
            get
            {
                if (ViewState["PageCount"] == null)
                {
                    ViewState["PageCount"] = 1;
                }
                return Convert.ToInt32(ViewState["PageCount"]);
            }
            set
            {
                ViewState["PageCount"] = value;
            }
        }

        /// <summary>
        /// 排序字段
        /// </summary>
        protected string SortField
        {
            get
            {
                if (ViewState["SortField"] == null)
                {
                    ViewState["SortField"] = "addtime";
                }
                return ViewState["SortField"].ToString();
            }
            set
            {
                ViewState["SortField"] = value;
            }
        }

        /// <summary>
        /// 排序方向
        /// </summary>
        protected string SortDirection
        {
            get
            {
                if (ViewState["SortDirection"] == null)
                {
                    ViewState["SortDirection"] = "desc";
                }
                return ViewState["SortDirection"].ToString();
            }
            set
            {
                ViewState["SortDirection"] = value;
            }
        }


        #endregion

        #region GetSortExpression GetTableColumnName

        protected string GetSortExpression(ExtAspNet.Grid grid, TableSchema.Table schema)
        {
            ExtAspNet.GridColumn column = grid.Columns[grid.SortColumnIndex];
            string columnName = GetTableColumnName(schema, column.SortField);
            return String.Format("{0} {1}", columnName, grid.SortDirection);
        }

        protected string GetTableColumnName(TableSchema.Table table, string propertyName)
        {
            foreach (TableSchema.TableColumn column in table.Columns)
            {
                if (column.PropertyName == propertyName)
                {
                    return column.ColumnName;
                }
            }
            return String.Empty;
        }

        #endregion

        /// <summary>
        /// 为删除Grid中选中项的按钮添加提示信息
        /// </summary>
        /// <param name="btn"></param>
        /// <param name="grid"></param>
        protected void ResolveDeleteGridItem(ExtAspNet.Button btn, ExtAspNet.Grid grid)
        {
            // 点击删除按钮时，至少选中一项
            btn.OnClientClick = grid.GetNoSelectionAlertInParentReference("至少选中一项！");
            btn.ConfirmText = String.Format("确定要删除&nbsp;<span style=\"color:red;font-weight:bold;\"><script>{0}</script></span>&nbsp;项纪录吗？", grid.GetSelectCountReference());
            btn.ConfirmTarget = ExtAspNet.Target.Top;
        }

        protected void ResolveDDL<T>(List<T> mys) where T : MyBaseClass, new()
        {

            ResolveDDL<T>(mys, -1, true);
        }

        protected void ResolveDDL<T>(List<T> mys, int currentId) where T : MyBaseClass, new()
        {
            ResolveDDL<T>(mys, currentId, true);
        }

        /// <summary>
        /// 将一个树型结构放在一个下列列表中可供选择
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="currentId"></param>
        /// <param name="mys"></param>
        protected void ResolveDDL<T>(List<T> mys, int currentId, bool addRootNode) where T : MyBaseClass, new()
        {
            if (addRootNode)
            {
                // 所有节点的TreeLevel加一，然后添加根节点
                foreach (T my in mys)
                {
                    my.TreeLevel += 1;
                }
                T root = new T();
                root.Name = "--根节点--";
                root.Id = 0;
                root.TreeLevel = 0;
                mys.Insert(0, root);
            }


            // currentId==-1表示当前节点不存在
            if (currentId != -1)
            {
                // 本节点不可点击（也就是说当前节点不可能是当前节点的父节点）
                // 并且本节点的所有子节点也不可点击，你想如果当前节点跑到子节点的子节点，那么这些子节点就从树上消失了
                bool startChileNode = false;
                int startTreeLevel = 0;
                foreach (T my in mys)
                {
                    if (my.Id == currentId)
                    {
                        startTreeLevel = my.TreeLevel;
                        my.Enabled = false;
                        startChileNode = true;
                    }
                    else
                    {
                        if (startChileNode)
                        {
                            if (my.TreeLevel > startTreeLevel)
                            {
                                my.Enabled = false;
                            }
                            else
                            {
                                startChileNode = false;
                            }
                        }
                    }
                }
            }
        }

        protected void UpdateOnlineUser(string username)
        {
            DateTime now = DateTime.Now;
            object lastUpdateTime = Session["OnlineUpdateTime"];
            if (lastUpdateTime == null || (Convert.ToDateTime(lastUpdateTime).Subtract(now).TotalMinutes > 5))
            {
                // 记录本次更新时间
                Session["OnlineUpdateTime"] = now;

                XOnline online = new Select().From<XOnline>()
                      .Where(XOnline.UserNameColumn).IsEqualTo(username)
                      .ExecuteSingle<XOnline>();

                if (online != null)
                {
                    online.UpdateTime = now;
                    online.Save();
                }
            }
        }

        protected void LoginOnlineUser(XUser user)
        {
            XOnline online = new Select().From<XOnline>()
                  .Where(XOnline.UserIdColumn).IsEqualTo(user.Id)
                  .ExecuteSingle<XOnline>();

            // 如果不存在，就创建一条新的记录
            if (online == null)
            {
                online = new XOnline();
            }
            DateTime now = DateTime.Now;
            online.UserId = user.Id;
            online.UserName = user.Name;
            online.UserRealName = user.RealName;
            online.IPAdddress = Request.UserHostAddress;
            online.LoginTime = now;
            online.UpdateTime = now;
            online.Save();

            // 记录本次更新时间
            Session["OnlineUpdateTime"] = now;
        }

        protected int GetOnlineCount()
        {
            return new Select().From<XOnline>()
                .Where(XOnline.UpdateTimeColumn).IsGreaterThan(DateTime.Now.AddMinutes(-15))
                .GetRecordCount();
        }

    }
}
